package exam.security;

import cn.hutool.json.JSONUtil;
import exam.service.impl.GroupAndMenuInfoServiceImpl;
import exam.utils.JwtUtils;
import exam.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class JwtLogoutSuccessHandle implements LogoutSuccessHandler {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    GroupAndMenuInfoServiceImpl groupAndMenuInfoService;
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//        System.out.println(httpServletRequest.getRequestURI());
        if(authentication != null){
            new SecurityContextLogoutHandler().logout(httpServletRequest,httpServletResponse,authentication);
        }


        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        httpServletResponse.setHeader(jwtUtils.getHeader(),"");

//        groupAndMenuInfoService.clearCurrentUserAuthorityInfo();

        Msg msg = Msg.success().setMessage("成功退出登录");

        outputStream.write(JSONUtil.toJsonStr(msg).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
